import { _decorator, instantiate, Label, Prefab, Sprite } from 'cc';
import { AbNames, EventMsgKes } from '../../Config/ResConfig';
import { GameData } from '../../Data/GameData';
import { ResManager } from '../../../../Framework/Scripts/Managers/ResManager';
import { UIMgr, UIType } from '../../../../Framework/Scripts/Managers/UIMgr';
import { GamePlayMap } from '../GamePlay/GamePlayMap';
import { ThemeMatchGameNextGroupRes } from '../../../AssetPackage/Props/Game/DT_ZT';
import { IBroadCorrectAnswerZt, IBroadCurEndZt, IBroadNextTopicZt, IEndInfoZt, IStatus, IThemeMatchStarBroad, ITopic, IUserAnswerZtRes, IUserEnterZtRes, IUserExitZtRes, IUserInfoZt, IZTScene } from '../proto/gameZt';
import { Answer, Respones, Stype } from '../../Config/GameCfg';
import { GameEndWin_Ctr } from './GameEndWin_Ctr';
import { GameEndLose_Ctr } from './GameEndLose_Ctr';
import { ViewMgr } from '../../../../Framework/Scripts/Managers/ViewMgr';
import { SceneMgr } from '../../../../Framework/Scripts/Managers/SceneMgr';
import { GameZt } from './GameZt';
const { ccclass, property } = _decorator;

/**
 * 主题赛游戏场景
 */
@ccclass('GamePlayZt_Ctr')
export class GamePlayZt_Ctr extends GameZt {
    spHeadL: Sprite;
    spHeadR: Sprite;
    labScoreL: Label;
    labScoreR: Label;
    time: number;
    labTime: any;
    gameType: number;
    ts_map: GamePlayMap;
    groupTpxs: ITopic[];
    lastData: any;
    protected onLoad(): void {
        this.InitUI();
        this.InitData();
    }

    start() {
       
        console.log('============GamePlayZt start ============');
    }

    protected onDestroy(): void {
        this.unRegisterEvent();
    }

    private InitUI(){
        this.registerEvent();

        this.spHeadL = this.ViewComponent('spTop/headL/spHead',Sprite);
        this.setHeadMat(this.spHeadL);
        this.spHeadR = this.ViewComponent('spTop/headR/spHead',Sprite);
        this.setHeadMat(this.spHeadR);
        this.labScoreL = this.ViewComponent('spTop/labL',Label);
        this.labScoreL.string = '';
        this.labScoreR = this.ViewComponent('spTop/labR',Label);
        this.labScoreR.string = '';
        this.labTime = this.ViewComponent('spTop/labTime',Label);
        this.labTime.string = '';


        let map = this.ViewNode('map');
        let pre = ResManager.inst.getAsset(AbNames.GamePlay,'Prefabs/GamePlay/GameMap',Prefab);
        let item: any = instantiate(pre)
        item.parent = map;
        this.ts_map = item.addComponent(GamePlayMap) as GamePlayMap;

        this.AddButtonListener('btnBack',this,this.OnBtnCloseClick1);
    }

    private InitData(){
        console.log('============GamePlay_Ctr==InitData==========')
        this.time = 0;
        this.setBgAni(0);
    }

    private registerEvent(){
        globalThis.gameMgr._eventTarget.on(EventMsgKes.msgThemeMatchUserEnter,this.onThemeMatchUserEnter,this);
        //  globalThis.gameMgr._eventTarget.on(EventMsgKes.msgThemeMatchGameRes,this.onThemeMatchGameRes,this);
         globalThis.gameMgr._eventTarget.on(EventMsgKes.msgThemeMatchGameAnswerBroadcast,this.onThemeMatchGameAnswerBroadcast,this);
         globalThis.gameMgr._eventTarget.on(EventMsgKes.msgGameAnswerEndBroadcast,this.onGameAnswerEndBroadcast,this);
         globalThis.gameMgr._eventTarget.on(EventMsgKes.msgThemeMatchGameNextBroadcast,this.onThemeMatchGameNextBroadcast,this);
         globalThis.gameMgr._eventTarget.on(EventMsgKes.msgThemeMatchGameEndBroadcast,this.onThemeMatchGameEndBroadcast,this);
         globalThis.gameMgr._eventTarget.on(EventMsgKes.msgThemeMatchGameNextGroupRes,this.onThemeMatchGameNextGroupRes,this);
         globalThis.gameMgr._eventTarget.on(EventMsgKes.msgThemeMatchExit,this.onThemeMatchGetDwReward,this);
         
    }

    private unRegisterEvent(){
        //  globalThis.gameMgr._eventTarget.off(EventMsgKes.msgThemeMatchGameRes,this.onThemeMatchGameRes,this);
         globalThis.gameMgr._eventTarget.off(EventMsgKes.msgThemeMatchGameAnswerBroadcast,this.onThemeMatchGameAnswerBroadcast,this);
         globalThis.gameMgr._eventTarget.off(EventMsgKes.msgGameAnswerEndBroadcast,this.onGameAnswerEndBroadcast,this);
         globalThis.gameMgr._eventTarget.off(EventMsgKes.msgThemeMatchGameNextBroadcast,this.onThemeMatchGameNextBroadcast,this);
         globalThis.gameMgr._eventTarget.off(EventMsgKes.msgThemeMatchGameEndBroadcast,this.onThemeMatchGameEndBroadcast,this);
         globalThis.gameMgr._eventTarget.off(EventMsgKes.msgThemeMatchGameNextGroupRes,this.onThemeMatchGameNextGroupRes,this);
         globalThis.gameMgr._eventTarget.off(EventMsgKes.msgThemeMatchExit,this.onThemeMatchGetDwReward,this);
    }

    public OnBtnCloseClick1(){
        this.stopTimeOut();
        super.OnBtnCloseClick1();
    }    

    //用户进入
    private onThemeMatchUserEnter(data:IUserEnterZtRes){
        if(this.hasProInObj(data,"code")){
            if(data.code === Respones.OK){
                let uid = data.uid;
                let avator = data.avator;
                if(GameData.inst.userInfo.userId === uid){
                    this.labScoreL.string = data.score.toString();
                    this.LoadRemoteImage(avator,this.spHeadL);
                }else{
                    this.labScoreR.string = data.score.toString();
                    this.LoadRemoteImage(avator,this.spHeadR);
                }
            }
        }
    }

    //定时器
    private setTimeOut(){
        // console.log('========setTimeOut=======',this.time);
        if(this.time <= 0){
            this.unschedule(this.setTimeOut);
            this.time = 0;
            //请求答题超时
            globalThis.gameMgr._GameZtMsg.sendTimeOutAnswer(this.ts_map.tid);
            return;
        }
        this.time--;
        this.labTime.string =this.time.toString(); 
    }

    //关闭定时器
    private stopTimeOut(){
        this.unschedule(this.setTimeOut);
        this.time = 0;
    }

    //展示一个题目
    private showOneTopic(){
        console.log('======当前组题目已经答完 主题赛1=====',this.groupTpxs.length);
        if(this.groupTpxs.length <= 0){
            console.log('======当前组题目已经答完 主题赛======');
            return;
        }
        let data:ITopic = this.groupTpxs.shift();
        console.log('========showOneTopic=========',data);
        this.time = data.time;
        
        globalThis.gameMgr.zts_answerStart = new Date().getTime();

        this.unschedule(this.setTimeOut);
        this.schedule(this.setTimeOut, 1);
        this.labTime.string = this.time.toString(); 
        this.ts_map.showTopic(data.time,data.topicId,data.tidx);
    }

    //主题赛场景
    public onThemeMatchGameRes(data:IThemeMatchStarBroad){
        console.log('==========onThemeMatchGameRes==========',data);
        //显示题目信息
        if(this.hasProInObj(data,'topics')){
            this.groupTpxs = [...data.topics];
            this.showOneTopic();
        }

        //显示用户得分
        let users = data.users;
        for (let i = 0; i < users.length; i++) {
            let cfg: IUserInfoZt = users[i];
            let score = cfg.score || 0;
            if(cfg.userId === GameData.inst.userInfo.userId){
                if(cfg.avator){
                    this.LoadRemoteImage(cfg.avator,this.spHeadL);
                }
                this.labScoreL.string = score.toString();
            } else {
                if(cfg.avator){
                    this.LoadRemoteImage(cfg.avator,this.spHeadR);
                }
                this.labScoreR.string = score.toString();
            }   
        }
    }

    //用户答题广播
    private onThemeMatchGameAnswerBroadcast(data:IUserAnswerZtRes){
        console.log('========onThemeMatchGameAnswerBroadcast============',data);
        if(!data)
            return;

        let code = data.code;
        if(code == Respones.OK){
            if(data.uid === GameData.inst.userInfo.userId){ //我自己答题
                this.ts_map.setAllUnClick();
                 //关闭定时器
                 this.stopTimeOut();
                if(data.status === Answer.Cur){  //答对
                    console.log('=========我自己答对==========')
                    this.ts_map.setChoicesData(data.cid,true,true);
                }else{ //答错
                    console.log('=========我自己答错==========')
                    this.ts_map.setChoicesData(data.cid,false,true);
                }
            }else{ //其他用户答题
                if(data.status === Answer.Cur){  //答对
                    console.log('=========其他用户答对==========')
                    this.ts_map.setChoicesData(data.cid,true,false);
                }else{ //答错
                    console.log('=========其他用户答错==========')
                    this.ts_map.setChoicesData(data.cid,false,false);
                }
            }
        }
    
    }

    //当前题目答完毕，广播正确答案
    private onGameAnswerEndBroadcast(data:IBroadCorrectAnswerZt){
        console.log('============onGameAnswerEndBroadcast============',data);

        //设置正确答案
        this.ts_map.setCurrentChoice(data.correctCid);

        let list = data.list;
        for (let i = 0; i < list.length; i++) {
            const item:IStatus = list[i];
            if(item.uid === GameData.inst.userInfo.userId){ //我自己答题
                this.ts_map.setAllUnClick();
                if(item.status === Answer.Cur){  //答对
                    console.log('=========我自己答对==========')
                    this.ts_map.setChoicesData(item.cid,true,true);
                }else{ //答错
                    console.log('=========我自己答错==========')
                    this.ts_map.setChoicesData(item.cid,false,true);
                }
            }else{ //其他用户答题
                if(item.status === Answer.Cur){  //答对
                    console.log('=========其他用户答对==========')
                    this.ts_map.setChoicesData(item.cid,true,false);
                }else{ //答错
                    console.log('=========其他用户答错==========')
                    this.ts_map.setChoicesData(item.cid,false,false);
                }
            }
        }

            //刷新我的积分
        for (let i = 0; i < list.length; i++) {
            const cfg:IStatus = list[i];
            if(cfg.uid === GameData.inst.userInfo.userId){
                this.labScoreL.string = cfg.score.toString();
            }else{
                this.labScoreR.string = cfg.score.toString();
            }
        }
    }

    //下一题
    private onThemeMatchGameNextBroadcast(data: IBroadNextTopicZt){
        console.log('=======onThemeMatchGameNextBroadcast==============',data);
        this.showOneTopic();
    }

    //结算
    private onThemeMatchGameEndBroadcast(data: IBroadCurEndZt){
        console.log('=======onThemeMatchGameEndBroadcast==============',data);
        if(!data)
            return;

       
        console.log('=======onThemeMatchGameEndBroadcast1===========',data.users);
        if(this.hasProInObj(data,'users')){
            let user = data.users;
            let isWin = false;

            if(GameData.inst.userInfo.userId === user[0].userId){
                if(user[0].score > user[1].score){
                    console.log('====我赢了===');
                    isWin = true;
                }else{
                    console.log('====我输了===');
                    isWin = false;
                }
            }
          
            let users = data.users;
            if(isWin){ //赢了
                let ts_node = UIMgr.inst.ShowUIView(AbNames.GamePlay,"Prefabs/GameZT/GameEndWin",UIType.UnFull) as GameEndWin_Ctr;
                ts_node.setDataWin(users);
            }else{ //输了
                let ts_node = UIMgr.inst.ShowUIView(AbNames.GamePlay,"Prefabs/GameZT/GameEndLose",UIType.UnFull) as GameEndLose_Ctr;
                ts_node.setDataLose(users);
            }
    
            //刷新我的积分
            for (let i = 0; i < users.length; i++) {
                const cfg:IEndInfoZt = users[i];
                if(cfg.userId === GameData.inst.userInfo.userId){
                    this.labScoreL.string = cfg.score.toString();
                }else{
                    this.labScoreR.string = cfg.score.toString();
                }
            }
        }
    
    }

    public onThemeMatchGameNextGroupRes(data:ThemeMatchGameNextGroupRes){
        let code = data.code;
        if(code === 0){
            this.InitData();
        }
    }

    //用户退出游戏
    public onThemeMatchGetDwReward(data:IUserExitZtRes){
        console.log('==========onThemeMatchGetDwReward============',data);
        let code = data.code;
        if(code === Respones.OK){
            //链接大厅的网络
            const callFunction = SceneMgr.inst.SetCallFun(SceneMgr.inst.showHallViwe);
            let call ={
                func: callFunction,
                path: "Prefabs/GameHall"
            }
            ViewMgr.inst.ConnectToHall(call);
        }
    }

    /**
     * 
     * @param type 1 是主题赛进入的 2 是好友赛进入的
     */
    public setGameType(type: number){
        console.log('=======setGameType=======',type);
        this.gameType = type;
    }
}